package com.roger.myHome.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import java.util.*;

/**
 * Created by admin on 2019/1/28.
 */
public class JwtUtil {
    public static final long EXPIRE = 1000 * 60 * 60 * 24;//token过期时间
    private static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";//secret：秘钥

    public static String getJwtToken(String userId, String loginName, long expire){

        String JwtToken = Jwts.builder()
                //设置JWT头
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置过期时间
                .setSubject("qlugcl-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                //设置token主体部分，存储用户信息
                .claim(Constants.USER_ID, userId)
                .claim("loginName", loginName)
                //秘钥加密部分
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }


    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static Claims checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return null;
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
            Claims claims = claimsJws.getBody();
            return claims;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        long expire = 1000 * 60 * 60;
        String jwtToken = getJwtToken("1234","admin",expire);
        try {
            Thread.sleep(1000 * 60 * 1);
            Claims claims = checkToken(jwtToken);
            String id = (String)claims.get(Constants.USER_ID);
            System.out.println(id);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
